// src/api/http.ts
import { BASE_URL, TENANT_ID } from '@/config'; // 导入基础 URL

// API响应基础接口
export interface ApiResponse<T = any> {
  code: number
  msg: string
  data: T
}

// 分页响应接口
export interface PageResponse<T> {
  code: number
  msg: string
  rows: T[]
  total: number
}

// 封装uni.request请求
interface RequestOptions {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: any;
  params?: Record<string, any>; // 添加 params 支持
  header?: Record<string, any>;
  timeout?: number;
}

const request = (options: RequestOptions): Promise<any> => {
  // 获取存储的token
  const token = uni.getStorageSync('token') || '';

  // 默认header
  const defaultHeader: Record<string, any> = {
    'Content-Type': 'application/json',
    'tenant-id': TENANT_ID,
    ...options.header
  };

  // 如果有token，则添加到Authorization头部
  if (token) {
    defaultHeader['Authorization'] = `Bearer ${token}`;
  }

  // 处理URL和params
  let url = BASE_URL + options.url;
  if (options.params && Object.keys(options.params).length > 0) {
    const queryString = Object.keys(options.params)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(options.params![key])}`)
      .join('&');
    url += (url.includes('?') ? '&' : '?') + queryString;
  }

  // 完整的请求选项
  const requestOptions: UniApp.RequestOptions & {
    url: string;
    header: Record<string, any>
  } = {
    url: url, // 使用处理后的URL
    method: options.method || 'GET',
    data: options.data || {},
    header: defaultHeader,
    timeout: options.timeout || 60000,
    success: () => { },
    fail: () => { }
  };


  // 返回Promise
  return new Promise((resolve, reject) => {
    requestOptions.success = (res: any) => {
      // 可以在这里统一处理响应状态码
      resolve(res.data);
    };

    requestOptions.fail = (err: any) => {
      // 可以在这里统一处理错误
      reject(err);
    };

    uni.request(requestOptions);
  });
};

export default request;